// BackupManager.java
import dao.DBConnection;
import pojo.Attendance;
import pojo.Department;
import pojo.Employee;

import java.sql.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class BackupManager {

    // 备份全部数据到指定文件（这里使用简单的文本格式，可根据需要调整为 CSV、JSON 等格式）
    public void backupData(String backupFilePath) {
        try (Connection conn = DBConnection.getConnection()) {
            // 备份员工、部门、考勤数据
            List<Employee> employees = backupEmployees(conn);
            List<Department> departments = backupDepartments(conn);
            List<Attendance> attendanceList = backupAttendance(conn);
            
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(backupFilePath))) {
                // 写入部门信息
                writer.write("DEPARTMENTS");
                writer.newLine();
                for(Department dept : departments) {
                    writer.write(dept.toString());
                    writer.newLine();
                }
                // 写入员工信息
                writer.write("EMPLOYEES");
                writer.newLine();
                for(Employee emp : employees) {
                    writer.write(emp.toString());
                    writer.newLine();
                }
                // 写入考勤信息
                writer.write("ATTENDANCE");
                writer.newLine();
                for(Attendance att : attendanceList) {
                    writer.write(att.toString());
                    writer.newLine();
                }
                writer.flush();
            }
            System.out.println("备份成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private List<Employee> backupEmployees(Connection conn) throws SQLException {
        List<Employee> list = new ArrayList<>();
        String sql = "SELECT * FROM employees";
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while(rs.next()){
                Employee emp = new Employee(
                    rs.getString("employee_id"),
                    rs.getString("name"),
                    rs.getString("gender"),
                    rs.getInt("age"),
                    rs.getString("department"),
                    rs.getString("position"),
                    rs.getDate("join_date"),
                    rs.getString("phone"),
                    rs.getString("email")
                );
                list.add(emp);
            }
        }
        return list;
    }
    
    private List<Department> backupDepartments(Connection conn) throws SQLException {
        List<Department> list = new ArrayList<>();
        String sql = "SELECT * FROM departments";
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while(rs.next()){
                Department dept = new Department(
                    rs.getString("department_name"),
                    rs.getString("description")
                );
                list.add(dept);
            }
        }
        return list;
    }
    
    private List<Attendance> backupAttendance(Connection conn) throws SQLException {
        List<Attendance> list = new ArrayList<>();
        String sql = "SELECT * FROM attendance";
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while(rs.next()){
                Attendance att = new Attendance(
                    rs.getString("employee_id"),
                    rs.getDate("attendance_date"),
                    rs.getString("status")
                );
                list.add(att);
            }
        }
        return list;
    }
    
    // 恢复数据：从备份文件中读取数据，并插入到数据库
    public void restoreData(String backupFilePath) {
        try (Connection conn = DBConnection.getConnection()) {
            conn.setAutoCommit(false);
            try (BufferedReader reader = new BufferedReader(new FileReader(backupFilePath))) {
                String line;
                String currentSection = "";
                while ((line = reader.readLine()) != null) {
                    if (line.equals("DEPARTMENTS") || line.equals("EMPLOYEES") || line.equals("ATTENDANCE")) {
                        currentSection = line;
                        continue;
                    }
                    // 根据当前部分解析数据并恢复
                    if (currentSection.equals("DEPARTMENTS")) {
                        String[] parts = line.split(",");
                        if(parts.length >=2){
                            Department dept = new Department(parts[0], parts[1]);
                            insertDepartment(conn, dept);
                        }
                    } else if (currentSection.equals("EMPLOYEES")) {
                        // 格式：employeeId,name,gender,age,department,position,joinDate,phone,email
                        String[] parts = line.split(",");
                        if(parts.length >=9){
                            Employee emp = new Employee(
                                parts[0],
                                parts[1],
                                parts[2],
                                Integer.parseInt(parts[3]),
                                parts[4],
                                parts[5],
                                java.sql.Date.valueOf(parts[6]),
                                parts[7],
                                parts[8]
                            );
                            insertEmployee(conn, emp);
                        }
                    } else if (currentSection.equals("ATTENDANCE")) {
                        // 格式：employeeId,date,status
                        String[] parts = line.split(",");
                        if(parts.length >=3){
                            Attendance att = new Attendance(
                                parts[0],
                                java.sql.Date.valueOf(parts[1]),
                                parts[2]
                            );
                            insertAttendance(conn, att);
                        }
                    }
                }
                conn.commit();
                System.out.println("数据恢复成功！");
            } catch (Exception e) {
                conn.rollback();
                e.printStackTrace();
            } finally {
                conn.setAutoCommit(true);
            }
        } catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
    private void insertDepartment(Connection conn, Department dept) throws SQLException {
        String sql = "INSERT INTO departments(department_name, description) VALUES (?, ?)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, dept.getDepartmentName());
            pstmt.setString(2, dept.getDescription());
            pstmt.executeUpdate();
        }
    }
    
    private void insertEmployee(Connection conn, Employee emp) throws SQLException {
        String sql = "INSERT INTO employees(employee_id, name, gender, age, department, position, join_date, phone, email) " +
                     "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, emp.getEmployeeId());
            pstmt.setString(2, emp.getName());
            pstmt.setString(3, emp.getGender());
            pstmt.setInt(4, emp.getAge());
            pstmt.setString(5, emp.getDepartment());
            pstmt.setString(6, emp.getPosition());
            pstmt.setDate(7, new java.sql.Date(emp.getJoinDate().getTime()));
            pstmt.setString(8, emp.getPhone());
            pstmt.setString(9, emp.getEmail());
            pstmt.executeUpdate();
        }
    }
    
    private void insertAttendance(Connection conn, Attendance att) throws SQLException {
        String sql = "INSERT INTO attendance(employee_id, attendance_date, status) VALUES (?, ?, ?)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, att.getEmployeeId());
            pstmt.setDate(2, new java.sql.Date(att.getDate().getTime()));
            pstmt.setString(3, att.getStatus());
            pstmt.executeUpdate();
        }
    }
}
